<template>
  <div class="oobox">
    <div id="Kline" :style="{ height: kheight }"></div>
    <div class="lgbox" :style="{ bottom: culbottom + 'px' }">
      <img class="lgimg" src="../../assets/logo1.png" alt="" />
    </div>
  </div>
</template>

<script>
import kLine from "klinecharts";
import { createSocket } from "../../common/_websocket";
export default {
  data() {
    return {
      culbottom: "30",
      kheight: "54vh",
      klinecharts: null,
      interval: "15",
      intervalaa: "15min",
      oldMsgParams: [],
      newWebSocket: createSocket(),
      symbolInfo: {
        symbolId: "",
        symbolName: "",
      },
    };
  },
  deactivated() {
    kLine.dispose("Kline");
    this.newWebSocket.close();
  },
  destroyed() {
    kLine.dispose("Kline");
    this.newWebSocket.close();
  },
  activated() {
    // this.kLineChart.loadMore(timestamp => {
    //     setTimeout(() => {
    //       const firstData = kLineChart.getDataList()[0]
    //       kLineChart.applyMoreData(generatedKLineDataList(timestamp, firstData.close, 100), true)
    //     }, 2000)
    //   })
    // this.kInit();
  },
  methods: {
    targetInterval(intervel) {
      this.interval = intervel;
      this.handleIntervalText();
      this.getKlineData();
      this.getMsgList();
      // if (intervel != 0) {
        // this.setTechnicalIndicator("BOLL");
      // }
      // this.$refs.trade.widget.applyOverrides({
      //     "paneProperties.legendProperties.showSeriesOHLC": false,
      //   })
    },
    setTechnicalIndicator2(arr) {
      this.culbottom = 80 * arr.length + 10;
      // console.log(arr);
      let allarr = ["MACD", "VOL", "KDJ", "RSI"];
      let retarr = allarr.filter((v) => !arr.includes(v));
      retarr.forEach((v) =>
        this.klinecharts.removeTechnicalIndicator("pane_" + v)
      );
      arr.forEach((v) => {
        this.klinecharts.createTechnicalIndicator(v, false, {
          id: "pane_" + v,
          height: 80,
          minHeihgt: 50,
          dragEnabled: false,
        });
        this.klinecharts.overrideTechnicalIndicator({
          name: v,
          styles: {
            margin: {
              top: 0.2,
              bottom: 0.1,
            },
            line: {
              size: 1,
              colors: [
                "rgb(94, 186, 137)",
                "#e7ce95",
                "#b2a1e5",
                "#f15a22",
                "#3649df",
              ],
            },
          },
        });
      });
    },
    setTechnicalIndicator(name) {
      if (name == "none") {
        this.klinecharts.removeTechnicalIndicator("candle_pane");
        return;
      }
      this.klinecharts.createTechnicalIndicator(name, false, {
        id: "candle_pane",
      });
      this.klinecharts.overrideTechnicalIndicator({
        name: name,
        styles: {
          margin: {
            top: 0.2,
            bottom: 0.1,
          },
          line: {
            size: 1,
            colors: [
              "rgb(94, 186, 137)",
              "#e7ce95",
              "#b2a1e5",
              "#f15a22",
              "#3649df",
            ],
          },
        },
      });
    },
    async getKlineData(endTime) {
      const ret = await this.$http({
        url: "/contract/contractkline/list",
        method: "post",
        data: {
          symbolId: this.symbolInfo.symbolId, //币对(合约)id
          symbolName: this.symbolInfo.symbolName, //合约/币对名称
          type: this.intervalaa, //k线类型
          // "dateFormat": "yyyy-MM-dd HH:mm:ss", //时间格式化标准
          querySize: 500, //查询条数
          // "skipSize": 0 //跳过条数
          endTime: endTime,
        },
      });
      if (ret.data.code === 0) {
        if (ret.data.data.length) {
          let dataList = ret.data.data.map((v) => {
            return {
              close: v[4],
              high: v[2],
              low: v[3],
              open: v[1],
              timestamp: +v[0],
              volume: v[5],
              volNum: v[9],
              highlowP: v[8],
              highlowN: v[7],
            };
          });
          try {
            let accuracy = dataList[0].close.toString().split(".")[1].length;
            this.klinecharts.setPriceVolumePrecision(+accuracy, +accuracy);
          } catch (error) {
            //
          }

          if (endTime) {
            this.handleDataList(dataList, "history");
          } else {
            this.handleDataList(dataList, "api");
          }
        }
      }
    },
    getMsgList() {
      this.newWebSocket.websocket.send(
        JSON.stringify({
          type: "unsubscribe", // 查询消息类型，固定值
          params: this.oldMsgParams,
        })
      );
      this.newWebSocket.websocket.send(
        JSON.stringify({
          type: "subscribe", // 查询消息类型，固定值
          params: [
            "Kline",
            this.symbolInfo.symbolName,
            this.intervalaa,
            "yyyy-MM-dd HH:mm:ss",
          ], //下标 0 -> 请求类型不可变值
          // 下标 1 -> 币对(合约) 名称
          // 下标 2 -> k线类型
          // 下标 3 -> 时间格式化标准
        })
      );
      this.oldMsgParams = [
        "Kline",
        this.symbolName,
        this.intervalaa,
        "yyyy-MM-dd HH:mm:ss",
      ];
    },
    socketConnect() {
      // if(this.zindex == 2){
      //   return
      // }
      if (this.zindex == 2) {
        this.getMsgList();
        return;
      }
      this.newWebSocket.init({
        url: `/contract/ws/info`,
        onopen: (msg, data) => {
          this.getMsgList();
        },
        onmessage: (data) => {
          let zdata = JSON.parse(data);
          if (zdata.params[0] == "Kline") {
            // this.zindex = 2;
            this.handleDataList(zdata.data, "socket");
          }
        },
        onclose: (data) => {
          console.log(data);
        },
      });
    },
    handleDataList(data, type) {
      if (type == "socket") {
        if (data.e === "Kline") {
          let result = data.k;
          let barsData = {
            timestamp: result.t,
            open: result.o,
            high: result.h,
            low: result.l,
            close: result.c,
            volume: result.v,
            volNum: result.V,
            highlowP: result.Q,
            highlowN: result.q,
          };
          // console.log(barsData)
          this.klinecharts.updateData(barsData);
        }
      } else if (type == "api") {
        this.klinecharts.applyNewData(data);
      } else if (type == "history") {
        this.klinecharts.applyMoreData(data);
      }
    },
    handleIntervalText() {
      if (this.interval == 1) {
        this.intervalaa = "1min";
      } else if (this.interval == 3) {
        this.intervalaa = "3min";
      } else if (this.interval == 5) {
        this.intervalaa = "5min";
      } else if (this.interval == 15) {
        this.intervalaa = "15min";
      } else if (this.interval == 30) {
        this.intervalaa = "30min";
      } else if (this.interval == 60) {
        this.intervalaa = "1h";
      } else if (this.interval == 120) {
        this.intervalaa = "2h";
      } else if (this.interval == 240) {
        this.intervalaa = "4h";
      } else if (this.interval == 360) {
        this.intervalaa = "6h";
      } else if (this.interval == 480) {
        this.intervalaa = "8h";
      } else if (this.interval == 720) {
        this.intervalaa = "12h";
      } else if (this.interval == "1D") {
        this.intervalaa = "1day";
      } else if (this.interval == "4320") {
        this.intervalaa = "3day";
      } else if (this.interval == "1W") {
        this.intervalaa = "1week";
      } else if (this.interval == "1M") {
        this.intervalaa = "1month";
      }
    },
    handleSumPrice(val) {
      if (+val >= 100000000) {
        let n = Math.floor((+val / 100000000) * 100) / 100;
        return n + this.$t("long.yi");
      } else if (+val >= 10000) {
        let n = Math.floor((+val / 10000) * 100) / 100;
        return n + this.$t("long.wan");
      } else {
        return +val;
      }
    },
    kInit(symbolInfo, index) {
      this.symbolInfo = symbolInfo;
      this.interval = localStorage.getItem("Kinterval") || 15;

      this.klinecharts = kLine.init("Kline");
      this.kheight = symbolInfo.height || "54vh";
      this.klinecharts.setStyleOptions({
        grid: {
          show: true,
          // 网格水平线
          horizontal: {
            show: true,
            size: 1,
            color: "#090A1B",
            // 'solid'|'dash'
            style: "dash",
            dashValue: [2, 2],
          },
          // 网格垂直线
          vertical: {
            show: true,
            size: 1,
            color: "#393939",
            // 'solid'|'dash'
            style: "dash",
            dashValue: [2, 2],
          },
        },
        candle: {
          // 蜡烛图上下间距，大于1为绝对值，大于0小余1则为比例
          margin: {
            top: 0.2,
            bottom: 0.1,
          },
          // 蜡烛图类型 'candle_solid'|'candle_stroke'|'candle_up_stroke'|'candle_down_stroke'|'ohlc'|'area'
          type: "candle_solid",
          // 蜡烛柱
          bar: {
            upColor: "#00A77F",
            downColor: "#ee6560",
            noChangeColor: "#888888",
          },
          // 面积图
          area: {
            lineSize: 2,
            lineColor: "#2196F3",
            value: "close",
            backgroundColor: [
              {
                offset: 0,
                color: "rgba(33, 150, 243, 0.01)",
              },
              {
                offset: 1,
                color: "rgba(33, 150, 243, 0.2)",
              },
            ],
          },
          priceMark: {
            show: true,
            // 最高价标记
            high: {
              show: true,
              color: "#D9D9D9",
              textMargin: 5,
              textSize: 10,
              textFamily: "Helvetica Neue",
              textWeight: "normal",
            },
            // 最低价标记
            low: {
              show: true,
              color: "#D9D9D9",
              textMargin: 5,
              textSize: 10,
              textFamily: "Helvetica Neue",
              textWeight: "normal",
            },
            // 最新价标记
            last: {
              show: true,
              upColor: "#00A77F",
              downColor: "#ee6560",
              noChangeColor: "#888888",
              line: {
                show: true,
                // 'solid'|'dash'
                style: "dash",
                dashValue: [4, 4],
                size: 1,
              },
              text: {
                show: true,
                size: 12,
                paddingLeft: 2,
                paddingTop: 2,
                paddingRight: 2,
                paddingBottom: 2,
                color: "#FFFFFF",
                family: "Helvetica Neue",
                weight: "normal",
                borderRadius: 2,
              },
            },
          },
          // 提示
          tooltip: {
            // 'always' | 'follow_cross' | 'none'
            showRule: "follow_cross",
            // 'standard' | 'rect'
            showType: "rect",
            labels: [
              this.$t("long.shijian"),
              this.$t("common.kai"),
              this.$t("long.gao"),
              this.$t("long.di"),
              this.$t("long.show"),
              this.$t("long.zhangdiee"),
              this.$t("long.zhangdiefu"),
              this.$t("long.chengjiaoliang1"),
              this.$t("long.chengjiaoe"),
            ],
            values: (kLineData) => {
              return [
                {
                  value: this.$formatDate(
                    new Date(kLineData.timestamp),
                    "MM/dd hh:mm"
                  ),
                },
                { value: kLineData.open },
                { value: kLineData.high },
                { value: kLineData.low },
                { value: kLineData.close },
                { value: kLineData.highlowN.toString() },
                {
                  value: `${kLineData.highlowP}%`,
                  color: kLineData.highlowP <= 0 ? "#EF5350" : "#26A69A",
                },
                { value: this.handleSumPrice(kLineData.volume) },
                { value: this.handleSumPrice(kLineData.volNum) },
                // { value: kLineData.open.toFixed(2) },
                // { value: kLineData.close.toFixed(2) },
                // {
                //   value: `${change.toFixed(2)}%`,
                //   color: change < 0 ? '#EF5350' : '#26A69A'
                // }
              ];
            },
            defaultValue: "n/a",
            rect: {
              zIndex: 9999,
              width: 200,
              paddingLeft: 6,
              paddingRight: 6,
              paddingTop: 6,
              paddingBottom: 6,
              offsetLeft: 8,
              offsetTop: 8,
              offsetRight: 8,
              borderRadius: 4,
              borderSize: 0,
              borderColor: "transparent",
              backgroundColor: "rgba(17, 17, 17, .9)",
            },
            text: {
              size: 12,
              family: "Helvetica Neue",
              weight: "normal",
              color: "#D9D9D9",
              marginLeft: 8,
              marginTop: 6,
              marginRight: 8,
              marginBottom: 4,
            },
          },
        },
        // 技术指标
        technicalIndicator: {
          margin: {
            top: 0.2,
            bottom: 0.1,
          },
          bar: {
            upColor: "#00A77F",
            downColor: "#ee6560",
            noChangeColor: "#888888",
          },
          line: {
            size: 1,
            colors: ["#FF9600", "#9D65C9", "#2196F3", "#E11D74", "#01C5C4"],
          },
          circle: {
            upColor: "#00A77F",
            downColor: "#ee6560",
            noChangeColor: "#888888",
          },
          // 最新值标记
          lastValueMark: {
            show: false,
            text: {
              show: false,
              color: "#ffffff",
              size: 12,
              family: "Helvetica Neue",
              weight: "normal",
              paddingLeft: 3,
              paddingTop: 2,
              paddingRight: 3,
              paddingBottom: 2,
              borderRadius: 2,
            },
          },
          // 提示
          tooltip: {
            // 'always' | 'follow_cross' | 'none'
            showRule: "always",
            // 'standard' | 'rect'
            showType: "standard",
            showName: true,
            showParams: true,
            defaultValue: "n/a",
            text: {
              size: 11,
              family: "Helvetica Neue",
              weight: "normal",
              color: "#8992AE",
              marginTop: 6,
              marginRight: 8,
              marginBottom: 0,
              marginLeft: 8,
            },
          },
        },
        // x轴
        xAxis: {
          show: true,
          height: null,
          // x轴线
          axisLine: {
            show: false,
            color: "#888888",
            size: 1,
          },
          // x轴分割文字
          tickText: {
            show: true,
            color: "#888888",
            family: "Helvetica Neue",
            weight: "normal",
            size: 12,
            paddingTop: 3,
            paddingBottom: 6,
          },
          // x轴分割线
          tickLine: {
            show: false,
            size: 1,
            length: 3,
            color: "#888888",
          },
        },
        // y轴
        yAxis: {
          show: true,
          width: null,
          // 'left' | 'right'
          position: "right",
          // 'normal' | 'percentage' | 'log'
          type: "normal",
          inside: false,
          reverse: false,
          // y轴线
          axisLine: {
            show: false,
            color: "#888888",
            size: 1,
          },
          // y轴分割文字
          tickText: {
            show: true,
            color: "#888888",
            family: "Helvetica Neue",
            weight: "normal",
            size: 11,
            paddingLeft: 3,
            paddingRight: 6,
          },
          // y轴分割线
          tickLine: {
            show: false,
            size: 1,
            length: 3,
            color: "#888888",
          },
        },
        // 图表之间的分割线
        separator: {
          size: 0,
          color: "#888888",
          fill: true,
          activeBackgroundColor: "rgba(230, 230, 230, .15)",
        },
        // 十字光标
        crosshair: {
          show: true,
          // 十字光标水平线及文字
          horizontal: {
            show: true,
            line: {
              show: true,
              // 'solid'|'dash'
              style: "dash",
              dashValue: [4, 2],
              size: 1,
              color: "#888888",
            },
            text: {
              show: true,
              color: "#D9D9D9",
              size: 12,
              family: "Helvetica Neue",
              weight: "normal",
              paddingLeft: 2,
              paddingRight: 2,
              paddingTop: 2,
              paddingBottom: 2,
              borderSize: 1,
              borderColor: "#505050",
              borderRadius: 2,
              backgroundColor: "#505050",
            },
          },
          // 十字光标垂直线及文字
          vertical: {
            show: true,
            line: {
              show: true,
              // 'solid'|'dash'
              style: "dash",
              dashValue: [4, 2],
              size: 1,
              color: "#888888",
            },
            text: {
              show: true,
              color: "#D9D9D9",
              size: 12,
              family: "Helvetica Neue",
              weight: "normal",
              paddingLeft: 2,
              paddingRight: 2,
              paddingTop: 2,
              paddingBottom: 2,
              borderSize: 1,
              borderColor: "#505050",
              borderRadius: 2,
              backgroundColor: "#505050",
            },
          },
        },
      });
      if(this.interval == -1){
        //分时
        this.klinecharts.setStyleOptions({
          candle: { type: "area" },
        });
        this.klinecharts.removeTechnicalIndicator("candle_pane");
      }else{
        this.setTechnicalIndicator("BOLL");
        this.handleIntervalText();
        this.klinecharts.overrideTechnicalIndicator({
        name: "MA",
        calcParams: [5, 10, 30, 60, 120],
      });
      }
      if (index != 2) {
        this.setTechnicalIndicator2(["MACD"]);
      }
      this.klinecharts.setOffsetRightSpace(12);
      this.klinecharts.setDataSpace(12);



      this.klinecharts.loadMore((timestamp) => {
        this.getKlineData(timestamp);
      });
      this.klinecharts.setScrollEnabled(false);
      let timer = setTimeout(() => {
        clearTimeout(timer);
        this.klinecharts.setScrollEnabled(true);
      }, 1000);
      this.getKlineData();
      this.socketConnect();
    },
  },
};
</script>

<style lang="scss" scoped>
.oobox {
  width: 100vw;
  height: 54vh;
  position: relative;
  .lgbox {
    position: absolute;
    bottom: 30px;
    left: 40px;
    transform: translate(-50%, -50%);
    display: flex;
    align-items: center;
    opacity: 0.15;
    .lgimg {
      width: 40px;
      margin-right: 2px;
    }
  }
}
#Kline {
  width: 100vw !important;
  // height: 54vh !important;
  // border: 2px solid red;
}
</style>
